fastlane_version "2.158.0"
default_platform :ios

platform :ios do
  ### MATCH
  desc "Fastlane Match AppStore"
  lane :setup_match_appstore do
    setup_circle_ci
    match_appstore
  end

  desc "Fastlane Match Enterprise"
  lane :setup_match_enterprise do
    setup_circle_ci
    match_enterprise
  end

  desc "Fastlane Match Development"
  lane :setup_match_development do
    setup_circle_ci
    match_development
  end  

  desc "Fastlane Match - App Store"
  private_lane :match_appstore do
    match(
      app_identifier: [
        "com.kickstarter.kickstarter",
        "com.kickstarter.kickstarter.RichPushNotifications"
      ],
      type: "appstore",
      git_url: "git@github.com:kickstarter/ios-certificates",
      team_id: "48YBP49Y5N",
      git_branch: "ksr",
      username: ENV["ITUNES_CONNECT_ACCOUNT"]
    )
  end

  desc "Fastlane Match - Development"
  private_lane :match_development do
    match(
      app_identifier: [
        "com.kickstarter.kickstarter.debug",
        "com.kickstarter.kickstarter.debug.RichPushNotifications"
      ],
      type: "development",
      git_url: "git@github.com:kickstarter/ios-certificates",
      team_id: "48YBP49Y5N",
      git_branch: "ksr",
      username: ENV["ITUNES_CONNECT_ACCOUNT"],
      force_for_new_devices: true
    )
  end

  desc "Fastlane Match - Enterprise"
  private_lane :match_enterprise do
    match(
      app_identifier: [
        "com.kickstarter.kickstarter.beta",
        "com.kickstarter.kickstarter.beta.RichPushNotifications",
        "com.kickstarter.kickstarter.kickalpha",
        "com.kickstarter.kickstarter.kickalpha.RichPushNotifications",
      ],
      type: "enterprise",
      git_url: "git@github.com:kickstarter/ios-certificates",
      team_id: "5DAN4UM3NC",
      git_branch: "ksr-enterprise",
      username: ENV["ITUNES_CONNECT_ACCOUNT"],
      force_for_new_devices: true
    )
  end

  ### BETA

  lane :beta_match_gym_s3 do
    setup_match_enterprise
    xcode_check
    beta_gym
    beta_s3
  end

  desc "Build Beta"
  lane :beta_gym do
    build_the_app(
      output_name: "KickBeta",
      export_method: "enterprise",
      configuration: "Internal Beta"
    )
  end

  desc "Upload Beta to S3"
  lane :beta_s3 do
    File.write('.FASTLANE_RELEASE_NOTES.tmp', changelog)

    sh "./beta-changelog.rb"

    upload_s3(
      ipa: "#{gym_dir}/KickBeta.ipa",
      dsym: "#{gym_dir}/KickBeta.app.dSYM.zip"
    )

    sh "./beta-post-s3.rb"
  end

  ### PRODUCTION

  lane :itunes_match_gym_deliver do
    setup_match_appstore
    xcode_check
    itunes_gym
    itunes_deliver
  end

  desc "Build Production"
  lane :itunes_gym do
    build_the_app(
      output_name: "Kickstarter",
      export_method: "app-store",
      configuration: "Release"
    )
  end

  desc "Upload to the App Store"
  lane :itunes_deliver do
    deliver(
      force: true,
      api_key_path: "./Frameworks/native-secrets/ios/app-store-connnect-auth.json",
      app_identifier: ENV["ITUNES_APP_IDENTIFIER"],
      app: ENV["ITUNES_APP_ID"],
      ipa: "#{gym_dir}/Kickstarter.ipa",
      team_name: ENV["ITUNES_TEAM_NAME"],
      skip_screenshots: true,
      skip_metadata: true,
      precheck_include_in_app_purchases: false
    )

    upload_symbols_to_crashlytics(
      gsp_path: "./Frameworks/native-secrets/ios/Firebase-Production/GoogleService-Info.plist",
      binary_path: "./bin/upload-symbols",
      dsym_path: "#{gym_dir}/Kickstarter.app.dSYM.zip"
    )

    slack(
      slack_url: ENV["SLACK_WEBHOOK"],
      message: slack_message(
        "app store",
        get_version_number(xcodeproj: "Kickstarter.xcodeproj", target: "Kickstarter-iOS"),
        get_build_number(xcodeproj: "Kickstarter.xcodeproj"),
        "App Store Connect 🚀"
      )
    )
  end

  ### ALPHA
  lane :alpha_match_gym do
    setup_match_enterprise
    xcode_check
    alpha_gym
  end

  desc "Build Alpha"
  lane :alpha_gym do
    build_the_app(
      output_name: "KickAlpha",
      export_method: "enterprise",
      configuration: "Internal Alpha"
    )
  end

  ### SHARED

  desc "Download App Store dSYMs and upload to Crashlytics"
  lane :refresh_dsyms do |options|
    download_dsyms(
      username: ENV["ITUNES_CONNECT_ACCOUNT"],
      app_identifier: ENV["ITUNES_APP_IDENTIFIER"],
      team_name: ENV["ITUNES_TEAM_NAME"],
      version: "latest"
    )

    clean_build_artifacts

    slack(
      slack_url: ENV["SLACK_WEBHOOK"],
      message: "Successfully refreshed dSYMs for the latest App Store version"
    )
  end

  private_lane :xcode_check do
    # Keep xcode version in sync with `.circleci/config.yml`
    xcodes(version: "16.4.0", select_for_current_build_only: true)
  end

  private_lane :build_the_app do |options|
    export_options = {}

    unless options[:configuration].eql? "Release"
      # Disable bitcode for enterprise builds
      export_options = {
        includeBitcode: false,
        compileBitcode: false
      }
    end

    gym(
      output_name: options[:output_name],
      export_method: options[:export_method],
      scheme: "Kickstarter-iOS",
      configuration: options[:configuration],
      export_options: export_options
    )
  end

  ### HELPERS
  ### Grabs the last commit message into a changelog
  private_lane :changelog do
    changelog_from_git_commits(
      commits_count: 1,
      date_format: "short"
    )
  end

  desc "Commit history from a given tag"
  lane :commit_history do |options|
    changelog_from_git_commits(
      between: [options[:tag], "main"],
      pretty: "- %s",
      date_format: "short",
      match_lightweight_tag: false,
      merge_commit_filtering: "exclude_merges"
    )
  end

  private_lane :upload_s3 do |options|
    aws_s3(
      bucket: ENV['AWS_BUCKET'],
      region: ENV['AWS_REGION'],
      ipa: options[:ipa],
      dsym: options[:dsym],
      path: "{CFBundleVersion}/",
      upload_metadata: true
    )
  end

  def gym_dir
    ENV["GYM_OUTPUT_DIRECTORY"] || "."
  end

  def slack_message(type, version_number, build_number, platform)
    "[#{type.upcase}] uploaded v#{version_number} (#{build_number}) of the Kickstarter iOS app to #{platform}"
  end

  after_all do |lane|
  end

  error do |lane, exception|
  end
end
